package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 登录校验切面类
 */

@Component
@Aspect
public class LoginAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //环绕通知，登录校验
    //切入点表达式：指定对哪些规则的方法进行增强
    //对某些包下的所有类的所有方法且有@LoginCheck注解的方法进行增强
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(loginCheck)")
    public Object loginCheck(ProceedingJoinPoint proceedingJoinPoint,LoginCheck loginCheck) throws Throwable{
        //获取request对象，从请求头中获取token
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) attributes;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("token");
        //判断token是否为空，为空则直接返回登录提示
        if(!StringUtils.hasText(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //token不为空，则查询redis,获取对应用户id
        String customerId = stringRedisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        //用户id不为空,则将用户id存入ThreadLocal中
        if(StringUtils.hasText(customerId)){
            AuthContextHolder.setUserId(Long.valueOf(customerId));
        }else{
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //执行业务方法
        return proceedingJoinPoint.proceed();
    }
}
